// pages/certify/certify.js
var QQMapWX = require('../../qqmap-wx-jssdk.min.js');
 
// 实例化API核心类
var qqmapsdk = new QQMapWX({
    key: '6FTBZ-OPECR-OYVWT-WULAV-V7VPQ-FAFCT' // 必填
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 提示交货日期
    buytime:'',
    // 地址信息
    name:'',
    phone:'',
    address:'',
    way:'',
    // 物品信息
    pic:'',
    title:'',
    value:"",
    deposit:"",
    day:"",
    sum:'',
    // 租用时间
    starttime:'',
    finishtime:'',
    newtime:'',
    // 订单信息
    orderid:'',
    ordertime:'',
    paytime:'',
    changetime:"",
    remark:'',
    // 快照照片
    buyarray:[],
    morepic:[],
    showpic:true,
    ismine:''
  },

  onLoad(options){
    var that = this;
    // console.log(options)
    if(options.ismine == "true"){
      this.setData({
        ismine:true
      })
    }else{
      this.setData({
        ismine:false
      })
    }

    this.setData({
      orderid:options.orderid
    })

    if(options.orderid && options.itemid){
        wx.request({
          url: 'http://127.0.0.1:8080/order/orderById',
          method:"POST",
          data:{orderid:options.orderid},
          success(res){
            if(res.data){
              var data = res.data[0];
              // console.log(data)
              var transactionPic = JSON.parse(data.transactionPic)
              that.setData({
                name:data.receiveName,
                address:data.deliveryAddress,
                way:data.deliveryMethod,
                day:data.rentDays,
                sum:data.rentPayment,
                // 租用时间
                buytime:data.rentEndTime,
                starttime:data.rentStartTime,
                finishtime:data.rentEndTime,
                newtime:data.rentEndTime,
                // 订单信息
                ordertime:data.orderGenTime,
                paytime:data.orderPayTime,
                changetime:data.deliveryTime,
                remark:data.orderRemark,
                //交易快照
                buyarray:transactionPic,
              })
              if(that.data.ismine){
                that.setData({
                  phone:data.receivePhone,
                })
              }
              if(transactionPic != null){
                that.setData({
                  showpic:false
                })
              }

            }
            // console.log(res)
          }
        })
        wx.request({
          url: 'http://127.0.0.1:8080/item/selectItemById',
          method:"POST",
          data:{itemid:options.itemid},
          success(res){
            // console.log(res)
            if(res.data){
              var data = res.data[0];
              data.itemPic = JSON.parse(data.itemPic)
              if(!that.data.ismine){
                that.setData({
                  phone:data.contactPhone
                })
              }
              that.setData({
                // 物品信息
                pic:data.itemPic[0],
                title:data.itemTitle,
                value:data.dayRent,
                deposit:data.deposit,
              })
            }
          }
        })
    }
    
    var nowtime = new Date().toJSON().substring(0, 10);
    this.setData({
      newtime:nowtime
    })
  },

// 添加商品快照
  addpic(e){
    let that = this;
    wx.chooseImage({
      count: 9,
      success(res){
        var morepic = that.data.morepic.concat(res.tempFilePaths);
        // console.log(morepic)
        that.setData({
          morepic:morepic,
        })
        //上传完成后把文件上传到服务器
        var arr = [];
        var  h = that.data.morepic.length;
        var i =0;
        for (i = 0; i < h; i++) {
        //上传文件
        // console.log(i,h)
          wx.uploadFile({
          url: 'http://127.0.0.1:8080/image/upload',
          filePath: that.data.morepic[i],
            name: "file",
            header: {
              "content-type": "multipart/form-data"
            },
            success: function ({ data: res }) {
              res = JSON.parse(res);
              const pic_url = 'http://127.0.0.1:8080/image/download?name=' + res.data
              arr.unshift(pic_url);
            },
            fail: function (err) {
              wx.showToast({
                title: "上传失败",
                icon: "error",
                duration: 2000
              })
            },
            complete: function (result) {
              // console.log(result.errMsg)
            }
          })
        }

        setTimeout(function(){
          var picurl = that.data.buyarray.concat(arr)
          wx.request({
            url: 'http://127.0.0.1:8080/order/updateTransactionPic',
            method:"POST",
            data:{
              orderid:that.data.orderid,
              picurls:JSON.stringify(picurl)
            },
            success(res){
              if(res.data){
                that.setData({
                  buyarray:picurl,
                  showpic:false,
                  morepic:[]
                })
              }
            }
          })
        },100)
      }
    })
  },
  //删除照片
  delpic(e){
    let that = this;
    var index = e.currentTarget.dataset.index;
    var del = this.data.buyarray
    wx.showModal({
      content: '是否删除该照片',
      title: '提示',
      success(res){
        if(res.confirm){
          del.splice(index,1)
          var len = del.length
          if(len == 0){
            del = [];
            that.setData({showpic:true})
          }
          console.log(del)
          wx.request({
            url: 'http://127.0.0.1:8080/order/delRentPic',
            method:"POST",
            data:{
              orderid:that.data.orderid,
              picurls:JSON.stringify(del)  
            },
            success(res){
              if(res.data){
                that.setData({
                  buyarray:del
                })
              }
            }
          })
          
          
        }
      },
    })
    
  },
  // 查看图片
  showpic(e){
    var index  =e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.buyarray[index],     //当前图片地址
      urls: this.data.buyarray,                 //所有要预览的图片的地址集合 数组形式
      success: function (res) {},
    })
  },
  // 展示地址
  showaddress(e){
    var _this = this;
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: _this.data.address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function(res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        //根据地址解析在地图上标记解析地址位置
        _this.setData({ // 获取返回结果，放到markers及poi中，并在地图展示
          markers: [{
            id: 0,
            title: res.title,
            latitude: latitude,
            longitude: longitude,
            iconPath: '/pic/地标.png',//图标路径
            width: 30,
            height: 30,
            // callout: { //可根据需求是否展示经纬度
            //   content: latitude + ',' + longitude,
            //   color: '#000',
            //   display: 'ALWAYS'
            // }
          }],
          poi: { //根据自己data数据设置相应的地图中心坐标变量名称
            latitude: latitude,
            longitude: longitude
          },
        });

        wx.openLocation({
          latitude:latitude,
          longitude:longitude,
          address: _this.data.address,
          name: _this.data.address,
          scale: 28,
        })
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {
        console.log(res);
      }
    })
  },
  // 联系电话
  callrent(){
    wx.makePhoneCall({
      phoneNumber: this.data.phone,
      success: (res) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  callregulor(){
    wx.makePhoneCall({
      phoneNumber: '1025555555',
      success: (res) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },


   // 续租选择日期
  newdate(e){
    this.setData({
      newtime:e.detail.value
    })
  },

  //续租
  formore(){
    var that = this;
    var data = this.data;
    if(data.newtime != data.finishtime){
      wx.request({
        url: 'http://127.0.0.1:8080/user/personInfo',
        method:"POST",
        data:{openid:wx.getStorageSync('openid')},
        success(res){
          var money = res.data[0].money
          wx.showModal({
          title: '确定续租到'+data.newtime,
          content:"用户余额:"+money,
          complete: (res) => {
            if (res.confirm) {
              //续租需要修改 续租时间 结束时间 总租用天数 计算租用金额  扣除金额 
              var time = (Date.parse(new Date(data.newtime))-Date.parse(new Date(data.finishtime)))/1000/60/60/24;
              //删除续租后的用户余额
              var left = money-(time*data.value);

              var nowtime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
                if( money <time*data.value){
                  wx.showToast({
                    title: '余额不足，无法续租',
                    icon:"none"
                  })
                }else{
                  //需要修改的订单信息
                  var data1={
                    orderid:that.data.orderid,
                    rentrenewtime:nowtime,
                    rentendtime:data.newtime,
                    day:data.day+time,
                    sum:(time*data.value)+data.sum
                  }
                  wx.request({
                    url: 'http://127.0.0.1:8080/order/rentnew',
                    method:"POST",
                    data:data1,
                    success(res){
                      if(res.data){
                        wx.request({
                          url: 'http://127.0.0.1:8080/user/updateMoney',
                          method:"POST",
                          data:{
                            openid:wx.getStorageSync('openid'),
                            money:left
                          },
                          success(res){
                            if(res.data){
                              wx.navigateBack({
                                delta: 2,
                                success: (res) => {
                                  wx.showToast({
                                    title: '续租成功',
                                    icon:"success"
                                  })
                                },
                              })
                            }
                          }
                        })
                      }
                    }
                  })
                }

            }
          }
        })
      
      }
    })
    }else{
      wx.showToast({
        title: '请选择续租时间',
        icon:"none"
      })
    }
  }



})